using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using XLFrame.NodeEditor;

namespace XLFrame
{
    /// <summary>
    /// 基于Newtonsoft.Json,对Unity的Color和向量序列化进行扩展
    /// </summary>
    public static class Json
    {
        /// <summary>
        /// 序列化unity值类型时不会丢失数据
        /// </summary>
        private static readonly UnityJsonConverter UnityJsonConverter = new UnityJsonConverter();
        /// <summary>
        /// 保证序列化unity对象时不会丢失数据
        /// </summary>
        private static readonly UnityObjectConverter UnityObjectConverter = new UnityObjectConverter();

        /// <summary>
        /// 序列化和反序列化的设置
        /// </summary>
        private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings()
        {
            // 序列化时保留object的type 这样反序列化时就不会丢失数据
            TypeNameHandling = TypeNameHandling.Auto,
            Converters = new List<JsonConverter>() { UnityJsonConverter , UnityObjectConverter }
        };

        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="formatting"></param>
        /// <returns></returns>
        public static string SerializeObject(object value, Formatting formatting = Formatting.None)
        {
            return JsonConvert.SerializeObject(value, formatting, JsonSerializerSettings);
        }

        /// <summary>
        /// 反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string value)
        {
            return JsonConvert.DeserializeObject<T>(value, JsonSerializerSettings);
        }

        /// <summary>
        /// 通过类型反序列化对象
        /// </summary>
        /// <param name="value"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object DeserializeObject(string value, System.Type type)
        {
            return JsonConvert.DeserializeObject(value, type, JsonSerializerSettings);
        }
    }

   
}
